package org.example.petitionplatformsystem.controller;

import org.example.petitionplatformsystem.Response;
import org.example.petitionplatformsystem.dao.model.Category;
import org.example.petitionplatformsystem.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RequestMapping("/admin_panel")
@RestController
public class categoryController {
    //栏目表的服务
    private final CategoryService categoryService;
    @Autowired
    public categoryController(CategoryService categoryService){
        this.categoryService = categoryService;
    }

    @PostMapping("/category")
    public Response<Void> addCategory(@RequestParam String name, @RequestParam String description) {
        Category category = new Category();
        category.setCategoryName(name);
        category.setDescription(description);
        if (categoryService.isCategoryExist(name)) {
            categoryService.addCategory(category);
            return Response.newSuccessResponse(null);
        }
        return Response.newFailResponse("Category already exists");
    }

    @DeleteMapping("/category/{categoryId}")
    public Response<Void> deleteCategory(@PathVariable long categoryId) {
        if (categoryService.deleteCategory(categoryId)) {
            return Response.newSuccessResponse(null);
        }
        return Response.newFailResponse("Category not found");
    }

    @PutMapping("/category/{categoryId}")
    public Response<Void> updateCategory(@PathVariable long categoryId, @RequestParam(required = false) String name, @RequestParam(required = false) String description) {
        Category category = categoryService.getCategoryById(categoryId);
        if (category == null) {
            return Response.newFailResponse("Category not found");
        }

        if (!Objects.equals(name, "")) {
            category.setCategoryName(name);

        }
        if (!Objects.equals(description, "")) {
            category.setDescription(description);

        }

        categoryService.updateCategory(category);
        return Response.newSuccessResponse(null);
    }
    @GetMapping("/getcategory")
    public Response<List<Category>> getCategory() {
        List<Category> category = categoryService.getAllCategories();
        return Response.newSuccessResponse(category);
    }
}
